<?php

class Newsfeed_model extends Model {
	
	function Newsfeed_model() {
		parent::Model();
	}
	
	
	// check if the session username has owner rights for the specified newsfeed
	function check_newsfeed_ownership($newsfeed_id = "-1") {
		$this->db->where('owner', $this->session->userdata('username'));
		$this->db->where('nf_id', $newsfeed_id);
		$query = $this->db->get('newsfeeds');
		
		if ($query->num_rows() == 1) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
	
	// check if the session username has owner rights for the specified newsfeed
	function get_newsfeed_property($newsfeed_id = "-1", $property = "title") {
		$this->db->select($property);
		$this->db->where('nf_id', $newsfeed_id);
		$query = $this->db->get('newsfeeds');
		
		if ($query->num_rows() == 1) {
			return $query->row()->$property;
		} else {
			return FALSE;
		}
	}
	
	
	function delete_newsfeed($newsfeed_id = "-1") {
		// delete post comments
		// delete posts
		// delete newsfeed
		$this->db->select('*');
		$this->db->where('nf_id', $newsfeed_id);
		$query = $this->db->get('newsfeeds');
		
		if ($query->num_rows() == 1) {
			echo "deleting newsfeed titled - " . $query->row()->title . "<br />";
		}
		
		
		$this->db->select('*');
		$this->db->from('posts');
		$this->db->join('newsfeeds', 'newsfeeds.nf_id = posts.nf_id');
		$this->db->where('newsfeeds.nf_id', $newsfeed_id);
		$query_p = $this->db->get();
		
		foreach ($query_p->result() as $post) {
			echo "posts found for this newsfeed: " . $query_p->num_rows() . " - " . $post->post . "<br />";
		}
		
		foreach ($query_p->result() as $post) {
			$this->db->select('*');
			$this->db->from('posts_comments');
			$this->db->join('posts', 'posts.p_id = posts_comments.p_id');
			$this->db->where('posts.p_id', $post->p_id);
			
			$query_pc = $this->db->get();
			
			foreach ($query_pc->result() as $comment) {
				echo "comments found for this post: " . $query_pc->num_rows() . " - " . $comment->comments  . "<br />";
			}
		}
		
	}
	
	
	function get_newsfeeds() {
		$owner = $this->session->userdata('username');
		$this->db->where('owner', $owner);
		$this->db->order_by('nf_created', 'desc');
		$result = $this->db->get('newsfeeds');
		
		return $result;
	}
	
	function create_newsfeed() {
		$new_newsfeed_insert_data = array(
			'owner' => $this->session->userdata('username'),
			'who' => $this->input->post('who'),
			'title' => $this->input->post('title'),
			'nf_created' => date('Y-m-d H:i:s'),
			'nf_updated' => date('Y-m-d H:i:s')
		);
		
		$insert = $this->db->insert('newsfeeds', $new_newsfeed_insert_data);
		return $insert;
	}
}

?>